<template>
  <div>
    <el-button v-if="!addFlag" class="button-new-tag" size="small" @click="add">+</el-button>
    <el-input
      v-if="addFlag"
      ref="saveTagInput"
      v-model="newTag"
      class="input-new-tag"
      size="small"
      @blur="save(true)"
    />
    <el-tag
      v-for="tag in tags"
      :key="tag"
      closable
      size="default"
      @close="closeTag(tag)"
    >
      {{ tag }}
    </el-tag>
  </div>
</template>
<script>
import _ from 'lodash'

export default {
  name: 'NameSpaceList',
  props: {
    instance: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      tags: [],
      addFlag: false,
      newTag: ''
    }
  },
  watch: {
    instance(val) {
      const tagsStr = this.instance.namespaceList
      if (tagsStr) {
        this.tags = tagsStr.split(',')
      } else {
        this.tags = []
      }
    }
  },
  created() {
  },
  methods: {
    add() {
      this.addFlag = true
      this.newTag = ''
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    save(isNew) {
      if (isNew && this.newTag === '') {
        this.addFlag = false
        return
      }

      const index = this.tags.indexOf(this.newTag)
      if (index !== -1) {
        return
      }
      this.tags.push(this.newTag)
      // 移除空
      this.tags = this.tags.filter(tag => tag !== '')
      this.addFlag = false

      const tagsStr = this.tags.join(',')
      const instance = _.clone(this.instance)
      instance['namespaceList'] = tagsStr
      this.$emit('save', instance)
    },
    closeTag(tag) {
      const index = this.tags.indexOf(tag)
      if (index !== -1) {
        this.$confirm('确定要删除该命名空间吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tags.splice(index, 1)
          this.save()
        })
      }
    }
  }
}
</script>
<style scoped>
  .el-tag{
    margin-left: 10px;
    margin-bottom: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 100px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
